package com.bytesizedhosting.api.android.darthcrap.widgets;

import android.app.AlertDialog;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

import com.bytesizedhosting.api.android.darthcrap.Constants;
import com.bytesizedhosting.api.android.darthcrap.ExtendedActivity;
import com.bytesizedhosting.api.android.darthcrap.R;
import com.bytesizedhosting.api.android.darthcrap.api.APIController;
import com.bytesizedhosting.api.android.darthcrap.api.APIData;
import com.bytesizedhosting.api.android.darthcrap.api.APIData.Account;

public class AccountUsageWidgetConfigurator extends ExtendedActivity {
	private int intNewWidgetID = AppWidgetManager.INVALID_APPWIDGET_ID;
	
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setResult(RESULT_CANCELED);
        setContentView(R.layout.account_usage_widget_configurator);        
        
        Bundle objExtras = getIntent().getExtras();
        if (objExtras != null) {
        	intNewWidgetID = objExtras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
        }
        
        if (intNewWidgetID == AppWidgetManager.INVALID_APPWIDGET_ID) {
        	closeConfigurator(false);
        }
        
        APIData objData = APIController.getData();
        int intErrorMessage = -1;
        if (objData == null) {
        	intErrorMessage = R.string.widgetconf_error_message_nodata;
        }
        else {
        	if (objData.getAccountCount() < 1) {
        		intErrorMessage = R.string.widgetconf_error_message_noseedboxes;
        	}
        }
        
        if (intErrorMessage != -1) {
        	AlertDialog.Builder objBuilder = new AlertDialog.Builder(this);
        	objBuilder.setTitle(R.string.widgetconf_error_title);
        	objBuilder.setMessage(intErrorMessage);
        	objBuilder.setNeutralButton(R.string.generic_ok,new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface objDialog, int intID) {
					closeConfigurator(false);
					objDialog.dismiss();
				}
			});
        	objBuilder.create().show();
        }
        else {
	        findViewById(R.id.btnCreate).setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View objView) {
					Object objBoxName = ((Spinner)findViewById(R.id.spnBoxes)).getSelectedItem();
					if (objBoxName != null) {
						String strBoxName = objBoxName.toString();
						saveWidgetData(objView.getContext(),intNewWidgetID,strBoxName);
						pushUpdate(objView.getContext(),intNewWidgetID,strBoxName);
						closeConfigurator(true);
					}
				}
			});
	        findViewById(R.id.btnCancel).setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View objView) {
					closeConfigurator(false);
				}
			});
	        
	        ArrayAdapter<CharSequence> objAdapter = new ArrayAdapter<CharSequence>(this,android.R.layout.simple_spinner_item);
	        for (Account objAccount : objData.getAccountIterator()) {
	        	objAdapter.add(objAccount.getServerName());
	        }
	        objAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	        ((Spinner)findViewById(R.id.spnBoxes)).setAdapter(objAdapter);
        }
    }
    
    private void saveWidgetData(Context objContext, int intWidgetID, String strBoxName) {
		SharedPreferences.Editor objEditor = objContext.getSharedPreferences(Constants.PREFS_FILE, Context.MODE_PRIVATE).edit();
		objEditor.putString(Constants.PREFS_KEY_WIDGET_BOXNAME_PREFIX + intWidgetID, strBoxName);
		objEditor.putBoolean(Constants.PREFS_KEY_WIDGET_ACTIVE_PREFIX + intWidgetID, true);
		objEditor.commit();
    }
    
    public static void deleteWidgetData(Context objContext, int intWidgetID) {
		SharedPreferences.Editor objEditor = objContext.getSharedPreferences(Constants.PREFS_FILE, Context.MODE_PRIVATE).edit();
		objEditor.remove(Constants.PREFS_KEY_WIDGET_BOXNAME_PREFIX + intWidgetID);
		objEditor.commit();
    }
    
    public static boolean hasWidgetData(Context objContext ,int intWidgetID) {
    	SharedPreferences objPreferences = objContext.getSharedPreferences(Constants.PREFS_FILE, Context.MODE_PRIVATE);
    	return hasWidgetData(objContext, intWidgetID, objPreferences); 
    }
    
    private static boolean hasWidgetData(Context objContext, int intWidgetID, SharedPreferences objPreferences) {
    	return objPreferences.getBoolean(Constants.PREFS_KEY_WIDGET_ACTIVE_PREFIX + intWidgetID, false);
    }
    
    public static String loadBoxName(Context objContext, int intWidgetID) {
    	SharedPreferences objPreferences = objContext.getSharedPreferences(Constants.PREFS_FILE, Context.MODE_PRIVATE);
    	String strBoxName = null;
    	if (hasWidgetData(objContext, intWidgetID, objPreferences)) {
	    	strBoxName = objPreferences.getString(Constants.PREFS_KEY_WIDGET_BOXNAME_PREFIX + intWidgetID, null);
	    	if (strBoxName != null) {
	    		if (strBoxName.trim().length() < 1) {
	    			strBoxName = null;
	    		}
	    	}
    	}
    	if (strBoxName == null) {
    		strBoxName = objContext.getResources().getString(R.string.generic_unknown);
    	}
    	return strBoxName;
    }
    
    private void pushUpdate(Context objContext, int intWidgetID, String strBoxName) {
    	AppWidgetManager objManager = AppWidgetManager.getInstance(objContext);
    	AccountUsageWidgetProvider.pushUpdate(objContext, objManager, intWidgetID, strBoxName);
    }
    
    private void closeConfigurator(boolean boolSuccess) {
    	Intent objResultIntent = new Intent();
    	objResultIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, intNewWidgetID);
    	setResult((boolSuccess?RESULT_OK:RESULT_CANCELED), objResultIntent);
    	finish();
    }
}